package com.hm.gateway.filters;


import com.hm.gateway.config.AuthProperties;
import com.hm.gateway.utils.JwtTool;
import com.hmall.common.exception.UnauthorizedException;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher= new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断传过来的路径是否需要拦截
        if(isExcludePath(request.getPath().toString())){
            return chain.filter(exchange);
        }
        //3.获取请求体中的token
        String token=null;
        List<String> authorization = request.getHeaders().get("authorization");
        //4.判断token是否为空，为空则拦截，不为空则放行
        if(!(authorization ==null) && !(authorization.isEmpty())){
            token=authorization.get(0);
        }
        //5.通过jwtTool工具包解析token，获取用户id
        Long userId= null;
        try{
         userId= jwtTool.parseToken(token);
        }catch (UnauthorizedException e){
            //拦截，用枚举将状态码设置为401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String userInfo=userId.toString();
        // 6.传递用户信息
        ServerWebExchange serverWebExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        return chain.filter(serverWebExchange);
    }
    private boolean isExcludePath(String path) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
